local ROT = require 'rot'

local state = ROT.Class:extend()

function state:init(game, play, opt)
    self.game = game
    self.play = play
    self.selected = nil
    self.title = opt and opt.title or 'Consume item'
    self.type = opt and opt.type or nil
end

local FIRST_KEY = ('a'):byte() - 1
local DIM = { 120, 120, 120 }
local BRIGHT = { 240, 240, 240 }

function state:update()
    local player = self.game.player
    local stuff = player.stuff
    local display = self.game.display
    display:clear()
    display:write(self.title, 1, 1)

    local j = 0
    for i = 1, #stuff do
        if stuff[i].consume
        and (self.type == nil or self.type == stuff[i].type) then
            j = j + 1
            display:write(
                string.char(
                i + FIRST_KEY) .. ') ' .. stuff[i].name .. (
                    stuff[i].count and stuff[i].count > 1 and
                    (' x' .. tostring(stuff[i].count)) or ''),
                1, 2 + j,
                self.selected == i and BRIGHT or DIM)
        end
    end

    if self.selected then
        item = player.stuff[self.selected]
        display:write(item.glyph, 40, 1, item.color)
        display:write(item.name, 42, 1, BRIGHT)
        display:write(item.info, 40, 3, DIM)
    else
        display:write('Nothing selected.', 40, 1, DIM)
    end

    local s = '(a-z selects, [esc] cancels, [enter] confirms)'
    display:write(s, display:getWidth() - #s, display:getHeight())

end

function state:keypressed(key)
    local game = self.game
    local player = self.game.player
    local stuff = player.stuff
    if key == '\27' then
        game:popState()
    elseif key == '\n' and self.selected then
        local item = stuff[self.selected]
        if item.count and item.count > 1 then
            item.count = item.count - 1
        else
            table.remove(stuff, self.selected)
        end
        game:popState()
        item.consume(player, game)
        game.scene:passTime(10)
    else
        local index = key:byte() - FIRST_KEY
        if stuff[index] and stuff[index].consume then
            self.selected = index
        end
    end
end

return state
